<template>
  <t-card :bordered="border">
    <t-space direction="vertical" style="width: 100%">
      <template v-if="searchBarData.length">
        <common-search-bar :data="searchBarData" @search="tableFn.search" @reset="tableFn.reset"></common-search-bar>
      </template>

      <template v-if="actionBarData.length">
        <common-action-bar :data="actionBarData" @action="onAction"></common-action-bar>
      </template>

      <t-table
        row-key="id"
        :data="commonIns.list.value"
        :columns="columns"
        :loading="isLoading"
        :pagination="commonIns.pagination.value"
        :selected-row-keys="commonIns.selectedRowKeys.value"
        resizable
        bordered
        stripe
        @page-change="tableFn.onPageChange"
        @select-change="tableFn.onSelectChange"
      >
      </t-table>
    </t-space>

    <slot></slot>
  </t-card>
</template>

<script lang="ts" setup>
import { EventType } from 'mitt';
import { TableRowData } from 'tdesign-vue-next';
import { onMounted, PropType } from 'vue';

import CommonActionBar, { ActionBarItem } from '@/components/common-action-bar/index.vue';
import CommonSearchBar, { SearchBarItem } from '@/components/common-search-bar/index.vue';
import { isLoading } from '@/hooks/common';
import { mitter } from '@/utils/mitt';

const props = defineProps({
  commonIns: {
    type: Object,
    default: () => {
      return { page: true };
    },
  },
  searchBarData: {
    type: Array as PropType<SearchBarItem[]>,
    default: () => [],
  },
  actionBarData: {
    type: Array as PropType<ActionBarItem[]>,
    default: () => [],
  },
  columns: {
    type: Array as PropType<TableRowData[]>,
    default: () => [],
  },
  border: {
    type: Boolean,
    default: () => true,
  },
});

const { actionFn, tableFn }: Recordable = props.commonIns;

const onAction = (type: string, item: ActionBarItem) => {
  if (type === 'click' && !actionFn[item.key]) {
    console.log(item.key, '不存在');
    return;
  }

  actionFn[item.key](item);
};

// 监听mitter事件，并根据事件类型执行相应的操作
mitter.on('*', (type: EventType, row: TableRowData) => {
  const fnMap: Recordable = {
    edit: () => {
      tableFn.edit(row);
    },
    delete: () => {
      tableFn.delete(row);
    },
    display: () => {
      tableFn.display(row, 1 - row.display);
    },
    displayed: () => {
      row.display = 1 - row.display;
    },
    resetpass: () => {
      tableFn.resetpass(row);
    },
  };
  if (fnMap[type.toString()]) {
    fnMap[type.toString()]();
  } else {
    console.log(type, '没有监听逻辑');
  }
});

// 组件挂载时，初始化表格数据
onMounted(() => {
  tableFn.getList();
});
</script>
